//
//  XHMyTrafficMoneyViewController.m
//  umibus
//
//  Created by 冷山 on 16/6/17.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "XHMyTrafficMoneyViewController.h"
#import "XHMyFinancialBenefitsViewController.h"
#import "XHTrafficUseViewController.h"
#import "XHTrafficBuyBackViewController.h"
#import "XHTrafficUseDetailViewController.h"
#import "XHOrderEarningViewController.h"

#import "XHTrafficMoneyCell.h"

#import "Services.h"

#import <SVPullToRefresh/SVPullToRefresh.h>

static const NSUInteger kPageSize = 20;
static const NSUInteger kPageInit = 0;

@interface XHMyTrafficMoneyViewController ()<UITableViewDelegate,UITableViewDataSource,XHTrafficMoneyCellDeleagte>

@property (weak, nonatomic) IBOutlet UIScrollView *ui_scrollView;
@property (weak, nonatomic) IBOutlet UIButton *ui_menuItem1;
@property (weak, nonatomic) IBOutlet UIButton *ui_menuItem2;
@property (weak, nonatomic) IBOutlet UIView *ui_menuItemTagView;

@property (strong, nonatomic) UITableView *ui_tableView1;
@property (strong, nonatomic) UITableView *ui_tableView2;

@property (strong, nonatomic) NSMutableArray *m_messagesArray;
@property (strong, nonatomic) NSMutableArray *m_messagesArray2;
@property (assign, nonatomic) NSUInteger page;
@property (assign, nonatomic) BOOL hasNextPage;
@property (assign, nonatomic) NSUInteger page2;
@property (assign, nonatomic) BOOL hasNextPage2;


@end

@implementation XHMyTrafficMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.ui_scrollView.bounces = NO;
    [self.ui_menuItem1 setTitleColor:[ColorManager colorWithHexString:@"#5997A4"] forState:UIControlStateSelected];
    [self.ui_menuItem2 setTitleColor:[ColorManager colorWithHexString:@"#5997A4"] forState:UIControlStateSelected];
    self.ui_tableView1=[[UITableView alloc] initWithFrame:CGRectMake(self.ui_scrollView.frame.size.width*0, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height) style:UITableViewStyleGrouped];
    self.ui_tableView1.delegate=self;
    self.ui_tableView1.dataSource=self;
    self.ui_tableView1.backgroundColor = [ColorManager colorWithHexString:@"F8F8F8"];
    [self.ui_tableView1 setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.ui_scrollView addSubview:self.ui_tableView1];
    
    self.ui_tableView2=[[UITableView alloc] initWithFrame:CGRectMake(self.ui_scrollView.frame.size.width*0, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height) style:UITableViewStyleGrouped];
    self.ui_tableView2.delegate=self;
    self.ui_tableView2.dataSource=self;
    self.ui_tableView2.backgroundColor = [ColorManager colorWithHexString:@"F8F8F8"];
    [self.ui_tableView2 setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.ui_scrollView addSubview:self.ui_tableView2];
    
    [self.ui_tableView1 registerNib:[UINib nibWithNibName:@"XHTrafficMoneyCell" bundle:nil] forCellReuseIdentifier:XHTrafficMoneyCellIdentifier];
    [self.ui_tableView2 registerNib:[UINib nibWithNibName:@"XHTrafficMoneyCell" bundle:nil] forCellReuseIdentifier:XHTrafficMoneyCellIdentifier];
    
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(0,0,65,44)];
    [button setTitle:@"理财收益" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button addTarget:self action:@selector(settingAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *settingItem=[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem=settingItem;

    
    [self menuItemAction:self.ui_menuItem1];
    self.page=kPageInit;
    [self.ui_tableView1 addInfiniteScrollingWithActionHandler:^{
        if (!self.hasNextPage)
        {
            //[PromptAction showErrorPrompt:@"暂无更多数据"];
        }
        if (self.m_messagesArray.count>=kPageSize){
            [self getUserMoneyFlowIndexToUsed:self.page+1];
            return;
        }
        [self.ui_tableView1.infiniteScrollingView stopAnimating];
    }];
    [self.ui_tableView1 addPullToRefreshWithActionHandler:^{
        self.page=kPageInit;
        [self getUserMoneyFlowIndexToUsed:self.page ];
    }];
    [PublicMethod setPullToRefreshView:self.ui_tableView1];
    
    [self.ui_tableView2 addInfiniteScrollingWithActionHandler:^{
        
        if (!self.hasNextPage2)
        {
            //[PromptAction showErrorPrompt:@"暂无更多数据"];
        }
        if (self.m_messagesArray2.count>=kPageSize)
        {
            [self getUserMoneyFlowIndexNoUsed:self.page2+1];
            return;
        }
        [self.ui_tableView2.infiniteScrollingView stopAnimating];
    }];
    [self.ui_tableView2 addPullToRefreshWithActionHandler:^{
        
        self.page2=kPageInit;
        [self getUserMoneyFlowIndexNoUsed:self.page2];
    }];
    [PublicMethod setPullToRefreshView:self.ui_tableView2];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.page = kPageInit;
    self.page2 = kPageInit;
    [self getUserMoneyFlowIndexToUsed:self.page];
    [self getUserMoneyFlowIndexNoUsed:self.page2];
}

//可用
- (void)getUserMoneyFlowIndexToUsed:(NSInteger)page
{
    page = self.page;
    if (!self.m_messagesArray)
    {
        [self showLoadingView];
    }
    [ServiceManager getUserMoneyFlowWithPageIndex:page type:@"NORMAL" success:^(NSDictionary *data) {
        if (page == kPageInit || self.m_messagesArray == nil)
        {
            self.m_messagesArray = [NSMutableArray array];
        }
        NSArray * datas = data[@"result"];
        if ([datas isKindOfClass:[NSArray class]])
        {
            if (datas.count>0)
            {
                self.page=page;
                [self.m_messagesArray addObjectsFromArray:datas];
            }
//            if (self.m_messagesArray.count ==0)
//            {
//                self.ui_tableView1.hidden = YES;
//            }
//            else
//            {
//                self.ui_tableView1.hidden = NO;
//            }
        }
        else
        {
            
        }
        [self.ui_tableView1 reloadData];
        [self.ui_tableView1.infiniteScrollingView stopAnimating];
        [PublicMethod setFinishRefreshView:self.ui_tableView1];
        [self performSelector:@selector(stopAnimate:) withObject:nil afterDelay:2.0];
        [self hideLoadingView];
    } failure:^(NSDictionary *data) {
        [self.ui_tableView1.infiniteScrollingView stopAnimating];
        [self.ui_tableView1.pullToRefreshView stopAnimating];
        [self hideLoadingView];
    }];
}

- (void)stopAnimate:(NSTimer*)timer
{
    [self.ui_tableView1.pullToRefreshView stopAnimating];
    [PublicMethod setPullToRefreshView:self.ui_tableView1];
}

//已用
-(void)getUserMoneyFlowIndexNoUsed:(NSInteger)page
{
    page = self.page2;
    if (!self.m_messagesArray2)
    {
        [self showLoadingView];
    }
    [ServiceManager getUserMoneyFlowWithPageIndex:page type:@"LAPSE" success:^(NSDictionary *data) {
        if (page == kPageInit || self.m_messagesArray2 == nil)
        {
            self.m_messagesArray2 = [NSMutableArray array];
        }
        NSArray * datas = data[@"result"];
        if ([datas isKindOfClass:[NSArray class]])
        {
            if (datas.count>0)
            {
                self.page2=page;
                [self.m_messagesArray2 addObjectsFromArray:datas];
            }
//            if (self.m_messagesArray2.count ==0)
//            {
//                self.ui_tableView2.hidden = YES;
//            }
//            else
//            {
//                self.ui_tableView2.hidden = NO;
//            }
        }
        else
        {
            
        }
        [self.ui_tableView2 reloadData];
        [self.ui_tableView2.infiniteScrollingView stopAnimating];
        [PublicMethod setFinishRefreshView:self.ui_tableView2];
        [self performSelector:@selector(stopAnimate2:) withObject:nil afterDelay:2.0];
        [self hideLoadingView];
    } failure:^(NSDictionary *data) {
        [self.ui_tableView2.infiniteScrollingView stopAnimating];
        [self.ui_tableView2.pullToRefreshView stopAnimating];
        [self hideLoadingView];
    }];
}
- (void)stopAnimate2:(NSTimer*)timer
{
    [self.ui_tableView2.pullToRefreshView stopAnimating];
    [PublicMethod setPullToRefreshView:self.ui_tableView2];
}


- (void)settingAction:(UIButton*)button
{
    XHMyFinancialBenefitsViewController * viewController = [[XHMyFinancialBenefitsViewController alloc]init];
    viewController.title = @"我的理财收益";
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)menuItemAction:(UIButton *)sender
{
    [self.ui_menuItem1 setSelected:NO];
    [self.ui_menuItem2 setSelected:NO];
    [sender setSelected:YES];
    [UIView animateWithDuration:0.3f animations:^{
        CGRect frame=self.ui_menuItemTagView.frame;
        frame.origin.x=sender.frame.origin.x;
        frame.size.width=sender.frame.size.width;
        self.ui_menuItemTagView.frame=frame;
    }];
    NSInteger tag=sender.tag;
    [self.ui_scrollView setContentOffset:CGPointMake(self.ui_scrollView.frame.size.width*tag, 0) animated:YES];
}
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([self.ui_menuItem1 isSelected])
    {
        CGRect frame=self.ui_menuItemTagView.frame;
        frame.origin.x=self.ui_menuItem1.frame.origin.x;
        frame.size.width=self.ui_menuItem1.frame.size.width;
        self.ui_menuItemTagView.frame=frame;
    }
    else
    {
        CGRect frame=self.ui_menuItemTagView.frame;
        frame.origin.x=self.ui_menuItem2.frame.origin.x;
        frame.size.width=self.ui_menuItem2.frame.size.width;
        self.ui_menuItemTagView.frame=frame;
    }
    //设置ScrollView的Size,Offset
    self.ui_scrollView.contentSize=CGSizeMake(self.ui_scrollView.frame.size.width*2, self.ui_scrollView.frame.size.height);
    self.ui_tableView1.frame=CGRectMake(self.ui_scrollView.frame.size.width*0, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height);
    self.ui_tableView2.frame=CGRectMake(self.ui_scrollView.frame.size.width*1, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height);
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger section = 0;
    if (tableView==self.ui_tableView1)
    {
        section = self.m_messagesArray.count;
    }
    else if (tableView==self.ui_tableView2)
    {
        section = self.m_messagesArray2.count;
    }
    
    return section;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger rows=1;
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    if (tableView==self.ui_tableView1)
    {
        XHTrafficMoneyCell * cell = [tableView dequeueReusableCellWithIdentifier:XHTrafficMoneyCellIdentifier];
        cell.ui_buyBack.tag = indexPath.section;
        cell.ui_orderButton.tag = indexPath.section;
        cell.ui_useButton.tag = indexPath.section;
        cell.delegate = self;
        NSDictionary * dic = self.m_messagesArray[indexPath.section];
        NSDictionary * fundDic = dic[@"fundProfile"];
        NSArray * operatorArray = fundDic[@"products"];
        cell.ui_useButton.hidden = NO;
        cell.ui_buyBack.hidden = NO;
        cell.ui_money.hidden = NO;
        cell.ui_moneyTwo.hidden = YES;
        cell.ui_time.text = [[NSDate dateWithString:dic[@"createTime"]] stringWithFormatter];
        cell.ui_money.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"principal"] doubleValue]];
        cell.ui_goodCount.text = [NSString stringWithFormat:@"%@/%@",fundDic[@"totalRemainCount"],fundDic[@"totalOriginalCount"]];
        
        NSMutableArray * array = [[NSMutableArray alloc]init];
        for (NSString * str in operatorArray)
        {
            if([str isEqualToString:@"10086"])
            {
                [array addObject:@"移动流量"];
            }
            else if ([str isEqualToString:@"10010"])
            {
                [array addObject:@"联通流量"];
            }
            else if ([str isEqualToString:@"10000"])
            {
                [array addObject:@"电信流量"];
            }
        }
        NSString * operator = [array componentsJoinedByString:@" "];
        
        cell.ui_goodsType.text = [NSString stringWithFormat:@"%@",operator];
        
        return cell;
    }
    else if (tableView==self.ui_tableView2)
    {
        XHTrafficMoneyCell * cell = [tableView dequeueReusableCellWithIdentifier:XHTrafficMoneyCellIdentifier];
        NSDictionary * dic = self.m_messagesArray2[indexPath.section];
        NSDictionary * fundDic = dic[@"fundProfile"];
        NSArray * operatorArray = fundDic[@"products"];
        cell.delegate = self;
        cell.ui_useButton.hidden = YES;
        cell.ui_buyBack.hidden = YES;
        cell.ui_money.hidden = YES;
        cell.ui_moneyTwo.hidden = NO;
        cell.ui_time.text = [[NSDate dateWithString:dic[@"createTime"]] stringWithFormatter];
        cell.ui_moneyTwo.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"principal"] doubleValue]];
        cell.ui_goodCount.text = [NSString stringWithFormat:@"%@/%@",fundDic[@"totalRemainCount"],fundDic[@"totalOriginalCount"]];
        NSMutableArray * array = [[NSMutableArray alloc]init];
        for (NSString * str in operatorArray)
        {
            if([str isEqualToString:@"10086"])
            {
                [array addObject:@"移动流量"];
            }
            else if ([str isEqualToString:@"10010"])
            {
                [array addObject:@"联通流量"];
            }
            else if ([str isEqualToString:@"10000"])
            {
                [array addObject:@"电信流量"];
            }
        }
        NSString * operator = [array componentsJoinedByString:@" "];
        cell.ui_goodsType.text = [NSString stringWithFormat:@"%@",operator];
        return cell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView==self.ui_tableView1)
    {
        NSDictionary * dic = self.m_messagesArray[indexPath.section];
        XHTrafficUseDetailViewController * viewController = [[XHTrafficUseDetailViewController alloc]init];
        viewController.title = @"理财流量详情";
        viewController.orderSn = dic[@"orderSn"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
    else if (tableView==self.ui_tableView2)
    {
        NSDictionary * dic = self.m_messagesArray2[indexPath.section];
        XHTrafficUseDetailViewController * viewController = [[XHTrafficUseDetailViewController alloc]init];
        viewController.title = @"理财流量详情";
        viewController.orderSn = dic[@"orderSn"];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0;
    if (section==0)
    {
        height=10;
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=217;
    return height;
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.ui_scrollView)
    {
        int x = scrollView.contentOffset.x/scrollView.frame.size.width;
        if (x==0)
        {
            [self menuItemAction:self.ui_menuItem1];
        }
        if (x==1)
        {
            [self menuItemAction:self.ui_menuItem2];
        }
    }
}

#pragma - mark - 使用理财流量跳转进去对应使用状态

- (void)selectIndex:(NSUInteger)index
{
    if (index==0)
    {
        [self menuItemAction:self.ui_menuItem1];
    }
    else if (index==1)
    {
        [self menuItemAction:self.ui_menuItem2];
    }
}

#pragma - mark XHTrafficMoneyCellDeleagte 去使用 回购

- (void)buyBackAction:(UIButton*)button
{
    XHTrafficBuyBackViewController * viewController = [[XHTrafficBuyBackViewController alloc]init];
    NSDictionary * dic = self.m_messagesArray[button.tag];
    viewController.title = @"流量回购";
    viewController.backInfo = dic;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)goBuyAction:(UIButton*)button
{
    XHTrafficUseViewController * viewController = [[XHTrafficUseViewController alloc]init];
    NSDictionary * dic = self.m_messagesArray[button.tag];
    NSDictionary * fund = dic[@"fundProfile"];
    viewController.title = @"理财流量选择";
    viewController.totalRemainCount = [fund[@"totalRemainCount"] integerValue];
    viewController.orderSn = dic[@"orderSn"];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)orderEarningAction:(UIButton*)button
{
    XHOrderEarningViewController * viewController = [[XHOrderEarningViewController alloc]init];
    if (self.ui_menuItem1.selected==YES)
    {
        NSDictionary * dic = self.m_messagesArray[button.tag];
        viewController.orderSn = dic[@"orderSn"];
    }
    else if (self.ui_menuItem2.selected==YES)
    {
        NSDictionary * dic = self.m_messagesArray2[button.tag];
        viewController.orderSn = dic[@"orderSn"];
    }
    viewController.title = @"订单收益";
    [self.navigationController pushViewController:viewController animated:YES];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
